//index.js
//获取应用实例
const app = getApp()
var server = require('../../utils/server');
import {
  init
} from "../../utils/init";
import {
  formatDateCN
} from "../../utils/util"

Page({
  data: {
    list: [],
    current: 1,
    pageSize: 10,
    allPage: 0,
    loading: false,
    scrollTop: 0,
    userInfo: {},
    tableData: [],
    columns: [],
    tableYHeight: 1000,
    token: null,
    isShow: true,
    showName: new Date().toLocaleDateString(),
    keyword: "",
    // 时段选择插件-开始
    isPickerRender: false,
    isPickerShow: false,
    startTime: "开始时间",
    endTime: "结束时间",
    pickerConfig: {
      endDate: true,                          // 是否需要结束时间，为true时显示开始时间和结束时间两个picker
      column: "minute",                       //可选的最小时间范围hour、minute、secend
      dateLimit: true,                        //是否现在时间可选范围，false时可选任意时间；未数字n时，范围是当前时间的最近n天
      initStartTime:'2023-01-01 12:32',    //picker初始时间，默认当前时间
      initEndTime: "2023-12-01 12:32",     //picker初始结束时间，默认当前时间
      limitStartTime: "2023-05-06 12:32",  //最小可选时间
      limitEndTime: "2055-05-06 12:32"     //最大可选时间
    },
    // 时段选择插件-结束
    keyword: "",
    showMoreSearchStatus: false,
    areaSearchList: [],
    cateUsernameSearchList: [],
    bussinessSearchList: [],
    permissionUsernameSearchList: [],
    showArea: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    indexArea: null,//选择的下拉列表下标
    showCateUsername: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    indexCateUsername: null,//选择的下拉列表下标
    showPermissionUsername: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    indexPermissionUsername: null,//选择的下拉列表下标
    showBussiness: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    indexBussiness: null,//选择的下拉列表下标
    searchStartDate: "",
    searchEndDate: "",
    statusSearchList: [
      {
        id: 1,
        sysValueName: "待推送",
      },
      {
        id: 2,
        sysValueName: "核价中",
      },
      {
        id: 3,
        sysValueName: "等待中",
      },
      {
        id: 4,
        sysValueName: "一次竞价",
      },
      {
        id: 5,
        sysValueName: "二次竞价",
      },
      {
        id: 7,
        sysValueName: "已完成",
      }
    ],
    showStatus: false,
    indexStatus: null,
    statusMap: null,
  },
  // 选择日期
  bindStartDateChange(e){
    let that = this
    this.setData({
      searchStartDate: e.detail.value
    })
    setTimeout(()=>{
      that.getList()
    },100)
  },
  bindEndDateChange(e){
    let that = this
    this.setData({
      searchEndDate: e.detail.value
    })
    setTimeout(()=>{
      that.getList()
    },100)
  },

  // 清空筛选条件
  clearSearch(){
    let that = this
    this.setData({
      indexArea: null,
      indexCateUsername: null,
      indexPermissionUsername: null,
      indexBussiness: null,
      keyword: "",
      searchStartDate: "",
      searchEndDate: "",
      indexStatus: null,
    })
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  showMoreSearch(){
    if(!this.data.userInfo || !this.data.userInfo.userType){
      return
    }
    this.getSysList()
    this.setData({
      showMoreSearchStatus: !this.data.showMoreSearchStatus
    })
  },
  bindblurKeyword(e){
    let that = this
    let keyword = e.detail.value
    that.setData({
      keyword: keyword
    })
    setTimeout(() => {
      that.getList()
    }, 100)
  },

  pickerShow: function() {
    this.setData({
      isPickerShow: true,
      isPickerRender: true,
      chartHide: true
    });
  },
  pickerHide: function() {
    this.setData({
      isPickerShow: false,
      chartHide: false
    });
  },

  bindPickerChange: function(e) {
    this.getData(this.data.sensorList[e.detail.value].id);
    this.setData({
      index: e.detail.value,
      sensorId: this.data.sensorList[e.detail.value].id
    });
  },
  setPickerTime: function(val) {
    let data = val.detail;
    this.setData({
      startTime: data.startTime,
      endTime: data.endTime
    });
  },
  
  // 授权
  getSubMsg(){
    let that = this
    // 授权订阅消息
    console.log("订阅授权")
    wx.requestSubscribeMessage({
      tmplIds: ['gM28ZeiMzmJkEhB2mXnCSS0eKtmsPKuKPXFeE4Pv1aE','CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0'], // 最多支持3条
      success(res) {
        console.log("订阅===》",res)
        // 'accept'表示用户同意订阅该条id对应的模板消息
        if (res['gM28ZeiMzmJkEhB2mXnCSS0eKtmsPKuKPXFeE4Pv1aE'] === 'accept' && res['CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0'] === 'accept') {
          // 用户同意订阅，调用云函数或服务器接口发送订阅消息
          console.log("订阅成功")
          that.doSubscribe()
        }
      }
    })
  },
  doSubscribe() {
    let params = {}
    server.post("/app/user/subscribeUserMsg", params).then(res => {
      if (res.key === 1000) {
        let userInfo = this.data.userInfo
        userInfo.isSubscribeMessage = 2
        wx.setStorageSync('userInfo', userInfo)
        this.setData({
          userInfo: userInfo
        })
      }
    });
  },

  goLogin(){
    wx.getUserProfile({
      desc: '用于完善用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.showLoading({
          title: '加载中',
          mask: true,
        })
        wx.login({
          success: (res1) => {
            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
            wx.navigateTo({
              url: '/pages/login/login?code=' + res1.code,
            })
          }
        });
      },
      complete: (res) => {
        this.data.loading = false;
      }
    })
  },

  getSearchStatusList(){
    let that = this
    let params = {}
    let userInfo = that.data.userInfo
    if(userInfo.userType == 2){
      // 开拓者
      params.sysLabelIds = 17
    }else if(userInfo.userType == 1){
      params.sysLabelIds = 16
    }
    server.post("/app/user/getSysLabelValueManageList", params).then(res => {
      if (res.key === 1000) {
        let statusList = []
        let list = res.result.data[params.sysLabelIds]
        let map = {}
        list.forEach(item => {
          let obj = {
            id: item.id,
            sysValueName: item.sysValueName,
          }
          statusList.push(obj)
          map[item.id] = item.sysValueName
        })
        that.getList()
        wx.setStorageSync('statusMap', map)
        that.setData({
          statusSearchList: statusList,
          statusMap: map,
        })
      }
    });
  },

  onLoad: function (options) {
  },
  onShow: function () {
    let that = this
    init.call(this);
    if(wx.getStorageSync('token')){
      this.setData({
        token: wx.getStorageSync('token')
      })
    }
    if(wx.getStorageSync('userInfo')){
      let userInfo = wx.getStorageSync('userInfo')
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        showName: userInfo.telephone,
      })
      this.resetPage()
      this.getSearchStatusList()
    }
  },
  
  /*页面相关事件处理函数--监听用户下拉动作*/
  onPullDownRefresh: function () {
    this.data.current = 1;
    this.data.pageSize = 10;
    this.setData({
      scrollTop: 0
    });
    this.resetPage();
    this.getList();
    wx.stopPullDownRefresh();
  },

  /*页面上拉触底事件的处理函数*/
  onReachBottom: function () {
    if (this.data.current + 1 > this.data.allPage) {
      return;
    } else {
      this.data.current = this.data.current + 1;
      this.setData({
        current: this.data.current
      });
      this.getList();
    }
  },
  
  // 获取数据列表
  resetPage() {
    this.data.current = 1;
    this.data.pageSize = 10;
    this.data.allPage = 0;
    this.setData({
      current: this.data.current,
      allPage: this.data.allPage,
      list: []
    });
  },
  getStatusName(item){
    let userInfo = this.data.userInfo
    let userId = userInfo.userId
    let statusMap = this.data.statusMap
    let statusName = ''
    if(userInfo.userType == 1){
      // 渠道商的订单状态
      if(item.status == 2){
        // 未提交核价
        statusName = statusMap[71]
        // 已提交核价并且用户id是自己的，才判断为已提交
        let a = ',' + item.submitCheckUserIds + ','
        let b = ',' + userId + ','
        if(item.isSubmitCheck && item.isSubmitCheck == 2 && a.indexOf(b) > -1){
          statusName = statusMap[72]
        }
        // 判断是否为重新推送的订单
        if(item.isBackPush && item.isBackPush == 2){
          statusName = statusMap[73]
          let a = ',' + item.submitCheckUserIds + ','
          let b = ',' + userId + ','
          if(a.indexOf(b) > -1){
            statusName = statusMap[72]
          }else{
            statusName = statusMap[71]
          }
        }
      } else if(item.status == 3){
        statusName = statusMap[72]
      } else if(item.status == 4){
        // 没有设定截止时间，展示等消息
        if(!item.biddingOneEndTime){
          statusName = statusMap[72]
        }else{
          // 开拓者没有分配渠道或者没有分配该渠道，展示等消息
          if(!item.biddingPushChannelUserIds){
            statusName = statusMap[72]
          }else{
            let a = ',' + item.biddingPushChannelUserIds + ','
            let b = ',' + userId + ','
            if(a.indexOf(b) > -1){
              let c = ',' + item.biddingFirstUserIds + ','
              if(c.indexOf(b) > -1){
                statusName = statusMap[75]
              }else{
                statusName = statusMap[74]
              }
            }else{
              statusName = statusMap[72]
            }
          }
        }
      } else if(item.status == 5){
        statusName = statusMap[75]
        if(item.biddingStartTwo && item.biddingStartTwo == 2){
          let a = ',' + item.biddingSecondUserIds + ','
          let b = ',' + userId + ','
          if(a.indexOf(b) > -1){
            statusName = statusMap[77]
          }else{
            statusName = statusMap[76]
          }
        }
      } else if(item.status == 7){
        statusName = statusMap[78]
      }
      if(item.isNextPush == 2 && item.pushUserIds && ((',' + item.pushUserIds + ',').indexOf(',' + this.data.userInfo.userId + ',') > -1)){
        statusName += '，您没有权利参与竞价'
      }
    }else if(userInfo.userType == 2){
      // 开拓者的订单状态
      if(item.status == 1){
        statusName = statusMap[79]
      } else if(item.status == 2){
        // 未收到核价的时候
        statusName = statusMap[80]
        // 判断是否为发布者重新推送的订单
        if(item.isBackPush && item.isBackPush == 2){
          statusName = statusMap[83]
        }
        //  已收到任一渠道商提交的核价
        if(item.isSubmitCheck && item.isSubmitCheck == 2){
          statusName = statusMap[81]
        }
      } else if(item.status == 3){
        statusName = statusMap[82]
      } else if(item.status == 4){
        if(!item.biddingOneEndTime){
          statusName = statusMap[85]
        }else{
          statusName = statusMap[86]
        }
      } else if(item.status == 5){
        statusName = statusMap[87]
      } else {
        statusName = statusMap[88]
      }
      if(item.isNextPush == 2 && item.pushUserIds && ((',' + item.pushUserIds + ',').indexOf(',' + this.data.userInfo.userId + ',') > -1)){
        statusName += '，您没有权利参与竞价'
      }
    }else{
      // 其他
      statusName = '未知'
    }
    return statusName;
  },
  getList() {
    let params = {}
    if(this.data.keyword){
      params.keyword = this.data.keyword
    }
    if(this.data.indexArea || this.data.indexArea == 0){
      params.area = this.data.areaSearchList[this.data.indexArea].id
    }
    if(this.data.indexStatus || this.data.indexStatus == 0){
      params.status = this.data.statusSearchList[this.data.indexStatus].id
    }
    if(this.data.indexBussiness || this.data.indexBussiness == 0){
      params.bussinessUsername = this.data.bussinessSearchList[this.data.indexBussiness].sysValueName
    }
    if(this.data.indexPermissionUsername || this.data.indexPermissionUsername == 0){
      params.permissionUsername = this.data.permissionUsernameSearchList[this.data.indexPermissionUsername].sysValueName
    }
    if(this.data.indexCateUsername || this.data.indexCateUsername == 0){
      params.cateName = this.data.cateUsernameSearchList[this.data.indexCateUsername].id
    }
    if(this.data.searchStartDate){
      params.startTime = new Date(this.data.searchStartDate).getTime()
    }
    if(this.data.searchEndDate){
      params.endTime = new Date(this.data.searchEndDate).getTime()
    }
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    server.post("/app/user/orderList", params).then(res => {
      if (res.key === 1000) {
        let tableData = []
        res.result.list.forEach(item => {
          item.createDate = formatDateCN(new Date(item.createTime))
          if(item.cateNames){
            let cateNameList = item.cateNames.split(";")
            item.cateNameList = cateNameList.splice(0, cateNameList.length - 1)
          }
          if(item.areaName){
            item.areaName = item.areaName.substring(0,1)
          }
          item.statusName = this.getStatusName(item)
          tableData.push(item)
        })
        let columns = [
          { title: '操作', key: 'statusCol', width: '350rpx' },
          { title: '状态', key: 'statusName', width: '350rpx' },
          { title: '项目名称', key: 'projectName', width: '400rpx' },
          { title: '时间', key: 'createDate', width: '350rpx' },
          { title: '品类', key: 'cateNames', width: '350rpx' },
          { title: '品牌', key: 'brands', width: '350rpx' },
          { title: '总数', key: 'totalNum', width: '350rpx' },
          { title: '总货值', key: 'totalPrice', width: '350rpx' },
        ]
        this.setData({
          columns: columns,
          tableData: tableData,
        })
      }
    });
    wx.hideLoading()

  },
  // 点击下拉显示框
  selectTapArea() {
    this.setData({
      showArea: !this.data.showArea
    });
  },
  // 点击下拉列表
  optionTapArea(e) {
    let that = this
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      indexArea: Index,
      showArea: !this.data.showArea
    });
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  selectTapStatus() {
    this.setData({
      showStatus: !this.data.showStatus
    });
  },
  optionTapStatus(e) {
    let that = this
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      indexStatus: Index,
      showStatus: !this.data.showStatus
    });
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  // 点击下拉显示框
  selectTapBussiness() {
    this.setData({
      showBussiness: !this.data.showBussiness
    });
  },
  // 点击下拉列表
  optionTapBussiness(e) {
    let that = this
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      indexBussiness: Index,
      showBussiness: !this.data.showBussiness
    });
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  // 点击下拉显示框
  selectTapPermissionUsername() {
    this.setData({
      showPermissionUsername: !this.data.showPermissionUsername
    });
  },
  // 点击下拉列表
  optionTapPermissionUsername(e) {
    let that = this
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      indexPermissionUsername: Index,
      showPermissionUsername: !this.data.showPermissionUsername
    });
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  // 点击下拉显示框
  selectTapCateUsername() {
    this.setData({
      showCateUsername: !this.data.showCateUsername
    });
  },
  // 点击下拉列表
  optionTapCateUsername(e) {
    let that = this
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      indexCateUsername: Index,
      showCateUsername: !this.data.showCateUsername
    });
    setTimeout(() => {
      that.getList()
    }, 100)
  },
  getSysList() {
    let params = {
      sysLabelIds: "2,3,7,8"
    }
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    server.post("/app/user/getSysLabelValueManageList", params).then(res => {
      if (res.key === 1000) {
        let data = res.result.data
        let cateUsernameSearchList = data[2]
        let areaSearchList = data[3]
        let bussinessSearchList = data[7]
        let permissionUsernameSearchList = data[8]
        this.setData({
          areaSearchList: areaSearchList,
          bussinessSearchList: bussinessSearchList,
          cateUsernameSearchList: cateUsernameSearchList,
          permissionUsernameSearchList: permissionUsernameSearchList,
        })
      }
    });
    wx.hideLoading()
  },
})